package com.example.monitor.util.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisPoolMap {

	private JedisPool jedisPool;
	private static RedisPoolMap redispoolmap;

	private RedisPoolMap() {

	}

	public static RedisPoolMap init() {
		if (redispoolmap == null) {
			synchronized (RedisPoolMap.class) {
				if (redispoolmap == null) {
					redispoolmap = new RedisPoolMap();
				}
			}
		}
		return redispoolmap;
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	private ThreadLocal<Jedis> jedisLocal = new ThreadLocal<Jedis>();
	private ThreadLocal<Integer> count = new ThreadLocal<Integer>();

	/**
	 * 获取jedis
	 * 
	 * @return
	 */
	public synchronized Jedis getJedis() {
		count.set(0);
		if (jedisLocal.get() == null) {
			jedisLocal.set(Get());
		}
		return jedisLocal.get();
	}

	private Jedis Get() {
		count.set(count.get() + 1);
		if (count.get() >= 10) {
			return null;
		} else {
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
			} catch (Exception e) {
				jedis = Get();
			}
			if (jedis == null) {
				jedis = Get();
			}
			return jedis;
		}

	}

	/**
	 * 释放资源
	 * 
	 * @param jedis
	 */
	@SuppressWarnings("deprecation")
	public synchronized void jedisRemove() {
		Jedis jedis = jedisLocal.get();
		if (jedis != null && jedisPool != null) {
			jedisPool.returnResourceObject(jedis);
		}
		jedisLocal.remove();
	}

}
